<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
        <!-- <el-button v-loading="loading" type="warning" @click="draftForm">
          草稿
        </el-button> -->
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <!-- 广告标题 -->
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <!-- 广告商 -->
                <el-col :span="12">
                  <el-form-item label-width="90px" label="广告商家:" class="postInfo-container-item">
                    <el-input v-model="postForm.publishName" style="width: 205px;" placeholder="输入广告商家">{{ publishName }}</el-input>
                  </el-form-item>
                </el-col>

                <!-- 发布时间 -->
                <el-col :span="12">
                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                    <el-date-picker v-model="publishTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="选择发布时间" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <!-- 关键词数量 -->
                <el-col :span="12">
                  <el-form-item label-width="90px" label="关键词等级:" class="postInfo-container-item">
                    <el-select v-model="postForm.keywordCount" placeholder="选择关键词等级">
                      <el-option 
                        v-for="count in keywordCountListOptions" 
                        :key="count" 
                        :label="count"
                        :value="count" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!-- 类型 -->
                <el-col :span="12">
                  <el-form-item label-width="120px" label="广告类型:" class="postInfo-container-item">
                    <el-select v-model="postForm.type" placeholder="选择类型">
                      <el-option 
                        v-for="item in typeListOptions" 
                        :key="item" 
                        :label="item" 
                        :value="item" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <!-- 具体关键词 -->
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="90px" label="具体关键词:" class="postInfo-container-item">
                    <el-tag
                      :key="tag"
                      v-for="tag in dynamicTags"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag)">
                      {{tag}}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="inputVisible"
                      v-model="inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm"
                      @blur="handleInputConfirm"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <!-- 基本广告费 -->
                <el-col :span="12">
                  <el-form-item label-width="90px" label="基本费用:" class="postInfo-container-item">
                    <el-select v-model="postForm.basePrice" placeholder="选择基本费用">
                      <el-option v-for="(item,index) in basepriceListOptions" :key="item+index" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!--总广告费-->
                <el-col :span="12">
                  <el-form-item label-width="120px" label="总体费用:" class="postInfo-container-item">
                    <label style="color: crimson; font-weight: 200;">
                      基本费用+关键词点击次数(5/次)
                    </label>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row>
                <!-- 开始/结束时间 -->
                <el-col :span="12">
                  <el-form-item label-width="90px" label="开始时间:" class="postInfo-container-item">
                    <el-date-picker v-model="startTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="开始日期时间" />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label-width="120px" label="结束时间:" class="postInfo-container-item">
                    <el-date-picker v-model="endTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="结束日期时间" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row>
                <el-col :span="12">
                <!-- 摘要 -->
                  <el-form-item style="margin-bottom: 40px;" label-width="90px" label="广告内容:" >
                    <el-input v-model="postForm.content" :rows="1" type="textarea" class="ad-textarea" autosize placeholder="请输入具体广告内容" />
                    <span v-show="contentLength" class="word-counter">{{ contentLength }}words</span>
                  </el-form-item> 
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <!-- 上传图片 -->
        <el-form-item label-width="90px" label="广告图片:" prop="image" style="margin-bottom: 30px;" class="postInfo-container-item">
          <Upload v-model="postForm.image" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Upload from '@/components/Upload/SingleImage'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky'
import { validURL } from '@/utils/validate'
import { fetchAdById } from '@/api/ad'
import { searchUser } from '@/api/remote-search'

const defaultForm = {
  status: 'draft',
  title: '', // 题目
  content: '', 
  image: '', // 图片
  publishTime: undefined,
  startTime: undefined,
  enndTime: undefined,
  id: undefined,
  publishName:'',
  type:'',
  basePrice:'',
  keywordCount: 1, //默认选择的关键词数量
  inputValue: ''
}
export default {
  name: 'AdDetail',
  components: {  MDinput, Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      dynamicTags: ['优惠打折'],
      inputVisible: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      publishName:'',
      inputValue:'',
      userListOptions: [],
      typeListOptions: ['健身', '美食', '游玩', '交通', '学习', '日用品'],
      keywordCountListOptions: [1, 2, 3, 4, 5],
      basepriceListOptions:[500,800,1200],
      rules: {
        image: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
      },
      tempRoute: {}
    }
  },
  computed: {
    contentLength() {
      return this.postForm.content.length
    },
    publishTime: {
      get() {
        return (+new Date(this.postForm.publishTime))
      },
      set(val) {
        this.postForm.publishTime = new Date(val)
      }
    },
    startTime: {
      get() {
        return (+new Date(this.postForm.startTime))
      },
      set(val) {
        this.postForm.startTime = new Date(val)
      }
    },
    endTime: {
      get() {
        return (+new Date(this.postForm.endTime))
      },
      set(val) {
        this.postForm.endTime = new Date(val)
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchAdData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchAdData(id) {
      fetchAdById(id).then(response => {
        this.postForm = response.data
        this.postForm.title += `   Ad Id:${this.postForm.id}`
        this.postForm.content += `   Ad Id:${this.postForm.id}`

        this.setTagsViewTitle()

        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = 'Edit Ad'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Ad'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: '成功',
            message: '发布广告成功',
            type: 'success',
            duration: 2000
          })
          this.postForm.status = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    },

    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/mixin";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.ad-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>